<template>
  <div class="chat-app">
    <div class="app-container">
      <!-- 加载状态 -->
      <!-- <Loading v-if="!inited" /> -->

      <!-- 主要内容 -->
      <div class="main-content">
        <!-- 侧边栏 -->
        <ChatSidebar
          v-show="showSidebar"
          :copy-right="'Dify AI'"
          :current-id="conversationStore.currConversationId"
          :list="conversationStore.conversationList"
          @current-id-change="handleConversationChange"
          @toggle-sidebar="toggleSidebar"
        />

        <!-- 聊天界面 -->
        <div class="chat-main" :class="{ 'full-width': !showSidebar }">
          <!-- 顶部头部栏 - 当侧边栏隐藏时显示 -->
          <div v-if="!showSidebar" class="chat-header">
            <div class="flex items-center space-x-3">
              <!-- 展开侧边栏按钮 -->
              <button
                @click="toggleSidebar"
                class="p-2 rounded-md hover:bg-gray-100 transition-colors duration-200"
              >
                <svg
                  class="w-5 h-5 text-gray-500"
                  fill="none"
                  stroke="currentColor"
                  viewBox="0 0 24 24"
                >
                  <path
                    stroke-linecap="round"
                    stroke-linejoin="round"
                    stroke-width="2"
                    d="M4 6h16M4 12h16M4 18h16"
                  />
                </svg>
              </button>

              <div
                class="w-14 h-14 bg-gradient-to-br to-blue-500 rounded-lg flex items-center justify-center"
              >
                <img src="@/assets/imgs/file-preview.png" alt="logo" class="w-full h-full" />
              </div>

              <!-- 标题 -->
              <h1 class="text-lg font-semibold text-gray-900">电价政策问答助手</h1>
            </div>
          </div>

          <ChatInterface
            :chat-list="chatList"
            :is-responding="isResponding"
            :feedback-disabled="false"
            @send="handleSend"
            @feedback="handleFeedback"
            @stop="handleStop"
            @regenerate="handleRegenerate"
          />
        </div>

        <!-- 调试器 (仅开发环境) -->
        <!-- <ChatDebugger v-if="isDevelopment" :is-responding="isResponding" /> -->
      </div>

      <!-- 侧边栏遮罩层 - 移动端使用 -->
      <div v-if="showSidebar && isMobile" class="sidebar-overlay" @click="toggleSidebar"></div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, computed, onUnmounted } from 'vue'
import { storeToRefs } from 'pinia'
import ChatInterface from '@/views/PolicyQA/chat/ChatInterface.vue'
import ChatSidebar from '@/views/PolicyQA/chat/ChatSidebar.vue'
import ChatDebugger from '@/views/PolicyQA/chat/ChatDebugger.vue'
// import Loading from '@/views/PolicyQA/base/Loading.vue'
import { useConversationStore } from '@/store/modules/conversation'
import { useChatStore } from '@/store/modules/chat'
import { useStreamingChat } from '@/composables/useStreamingChat'
import { fetchConversations, fetchChatList, updateFeedback } from '@/service'
import type { VisionFile } from '@/types/app'

// 初始化状态
const inited = ref(false)
const isDevelopment = ref(import.meta.env.DEV)

// 检测是否为移动设备
const isMobile = computed(() => {
  return window.innerWidth < 768
})

// 侧边栏显示状态 - 移动端默认隐藏，桌面端默认显示
const showSidebar = ref(!isMobile.value)

// 使用 stores
const conversationStore = useConversationStore()
const chatStore = useChatStore()

// 使用流式聊天组合式函数
const { isResponding, sendStreamingMessage, abortStreaming, regenerateLastResponse } =
  useStreamingChat()

// 从 store 获取响应式数据
const { chatList } = storeToRefs(chatStore)

// 初始化应用
const initApp = async () => {
  try {
    console.log('开始初始化应用...')
    // // 获取token
    // const token = await getToken()
    // console.log('token:', token)
    // // 设置token
    // localStorage.setItem('token', token.data.token)

    // 获取对话列表
    const conversationsResponse = await fetchConversations()
    console.log('API 响应:', conversationsResponse)

    // 处理 API 响应结构
    let conversations
    if (Array.isArray(conversationsResponse)) {
      conversations = conversationsResponse
    } else if (
      conversationsResponse &&
      typeof conversationsResponse === 'object' &&
      'data' in conversationsResponse
    ) {
      conversations = (conversationsResponse as any).data
    } else {
      conversations = []
    }

    console.log('处理后的对话列表:', conversations)

    // 更新 store
    conversationStore.setConversationList(conversations)

    // 如果有对话，设置当前对话
    if (conversations.length > 0) {
      conversationStore.setCurrConversationId(conversations[0].id)
    }

    inited.value = true
    console.log('应用初始化完成')
  } catch (error) {
    console.error('初始化应用失败:', error)
    inited.value = true // 即使失败也要显示界面
  }
}

// 切换侧边栏显示状态
const toggleSidebar = () => {
  showSidebar.value = !showSidebar.value
}

// 监听窗口大小变化，调整侧边栏显示状态
const handleResize = () => {
  const mobile = window.innerWidth < 768
  if (mobile && showSidebar.value) {
    // 移动端自动隐藏侧边栏
    showSidebar.value = false
  } else if (!mobile && !showSidebar.value) {
    // 桌面端自动显示侧边栏
    showSidebar.value = true
  }
}

// 处理对话切换时在移动端自动隐藏侧边栏
const handleConversationChange = (conversationId: string) => {
  console.log('切换对话:', conversationId)

  if (conversationId === '-1') {
    // 新建对话
    conversationStore.createNewChat()
    chatStore.clearChatList()
  } else {
    // 切换到现有对话
    conversationStore.setCurrConversationId(conversationId)
  }

  // 移动端切换对话后自动隐藏侧边栏
  if (isMobile.value) {
    showSidebar.value = false
  }
}

// 刷新聊天列表的统一函数
const refreshChatList = async (conversationId: string, forceRefresh: boolean = false) => {
  if (!conversationId || conversationId === '-1') {
    console.log('⚠️ 跳过刷新：无效的对话ID', conversationId)
    return
  }

  try {
    console.log('🔄 刷新聊天列表:', {
      conversationId,
      forceRefresh,
      currentConversationId: conversationStore.currConversationId,
      currentChatListLength: chatStore.chatList.length,
      isNewConversation: conversationStore.isNewConversation
    })

    // 获取聊天记录，增加限制数量确保获取到所有消息
    const chatDataResponse = await fetchChatList(conversationId, {
      limit: 100, // 增加限制数量
      lastId: '',
      firstId: ''
    })

    // 处理 API 响应结构
    let chatData
    if (Array.isArray(chatDataResponse)) {
      chatData = chatDataResponse
    } else if (
      chatDataResponse &&
      typeof chatDataResponse === 'object' &&
      'data' in chatDataResponse
    ) {
      chatData = (chatDataResponse as any).data
    } else {
      chatData = []
    }

    console.log('📥 获取到的聊天数据:', chatData)

    // 处理文件信息的统一函数
    const processFiles = (item: any) => {
      const files: any[] = []

      if (item.message_files && Array.isArray(item.message_files)) {
        files.push(...item.message_files)
      }

      if (item.files && Array.isArray(item.files)) {
        files.push(...item.files)
      }

      return files.map((file: any) => ({
        id: file.id || file.upload_file_id || `file_${Date.now()}_${Math.random()}`,
        name: file.name || file.filename || file.id,
        type: file.type || file.mime_type || 'application/octet-stream',
        url: file.url || file.download_url,
        size: file.size,
        belongs_to: file.belongs_to || 'user'
      }))
    }

    // 生成新的聊天列表
    const newChatList: any[] = []

    if (chatData && Array.isArray(chatData)) {
      chatData.forEach((item: any) => {
        // 添加用户提问
        if (item.query) {
          const userFiles = processFiles(item)
          const userMessage: any = {
            id: `${item.id}_query`,
            content: item.query,
            isAnswer: false,
            message_files: userFiles.filter((f) => f.belongs_to === 'user' || !f.belongs_to)
          }

          // 如果有AI助手的文件，也添加到files字段用于显示
          const assistantFiles = userFiles.filter((f) => f.belongs_to === 'assistant')
          if (assistantFiles.length > 0) {
            userMessage.files = assistantFiles
          }

          newChatList.push(userMessage)

          if (userFiles.length > 0) {
            console.log(`✅ 用户消息 ${item.id}_query 包含 ${userFiles.length} 个文件`)
          }
        }

        // 添加 AI 回复
        if (item.answer) {
          const aiFiles = processFiles(item)
          const aiMessage: any = {
            id: item.id,
            content: item.answer,
            isAnswer: true,
            agent_thoughts: item.agent_thoughts || [],
            message_files: aiFiles.filter((f) => f.belongs_to === 'user'),
            // 将AI生成的文件添加到files字段，用于在消息内容下方显示
            files: aiFiles.filter((f) => f.belongs_to === 'assistant' || !f.belongs_to)
          }

          newChatList.push(aiMessage)

          if (aiFiles.length > 0) {
            console.log(`✅ AI消息 ${item.id} 包含 ${aiFiles.length} 个文件`)
            console.log('文件详情:', aiFiles)
          }
        }
      })
    }

    console.log('📋 生成的聊天列表:', newChatList)
    console.log('📊 聊天列表统计:', {
      总消息数: newChatList.length,
      用户消息: newChatList.filter((m) => !m.isAnswer).length,
      AI消息: newChatList.filter((m) => m.isAnswer).length,
      包含文件的消息: newChatList.filter(
        (m) => (m.files && m.files.length > 0) || (m.message_files && m.message_files.length > 0)
      ).length
    })

    // 更新聊天列表
    chatStore.setChatList(newChatList)
    return newChatList
  } catch (error) {
    console.error('❌ 刷新聊天列表失败:', error)
    throw error
  }
}

// 监听当前对话 ID 变化
watch(
  () => conversationStore.currConversationId,
  async (newId) => {
    if (newId && newId !== '-1') {
      try {
        console.log('🔄 对话ID变化，加载对话:', newId)
        await refreshChatList(newId)
      } catch (error) {
        console.error('❌ 加载对话失败:', error)
      }
    } else if (newId === '-1') {
      // 新对话，清空聊天列表
      console.log('🆕 新建对话，清空聊天列表')
      chatStore.clearChatList()
    }
  }
)

// 处理发送消息
const handleSend = async (message: string, files: VisionFile[]) => {
  try {
    // 记录当前对话ID，用于后续判断是否为新对话
    const isNewConversation = conversationStore.isNewConversation

    // 使用统一的流式消息发送接口
    await sendStreamingMessage(message, files, {
      onProgress: (progress) => {
        console.log('消息发送进度:', progress)
      },
      onConversationCreated: async (conversationId) => {
        console.log('新对话已创建:', conversationId)

        // 如果是新对话，需要在对话创建后立即刷新聊天列表
        if (isNewConversation) {
          console.log('🔄 新对话创建，准备刷新聊天列表')

          // 等待一小段时间确保服务器端数据已保存
          setTimeout(async () => {
            try {
              console.log('🔄 新对话创建，刷新聊天列表')
              await refreshChatList(conversationId, true)
            } catch (error) {
              console.error('❌ 刷新新对话聊天记录失败:', error)
            }
          }, 1500) // 增加延迟时间，确保服务器端数据已保存
        }
      },
      onMessageCompleted: async (conversationId, messageId) => {
        console.log('💬 消息完成回调:', { conversationId, messageId })

        // 消息完成后，验证聊天列表以确保消息正确显示
        if (conversationId && conversationId !== '-1') {
          try {
            console.log('🔄 消息完成，验证聊天列表')

            // 短暂延迟后检查并刷新消息
            setTimeout(async () => {
              try {
                // 检查当前聊天列表和服务器数据是否一致
                const currentList = await refreshChatList(conversationId, false)

                console.log('📊 消息完成验证:', {
                  currentCount: chatStore.chatList.length,
                  refreshedCount: currentList?.length || 0
                })
              } catch (error) {
                console.error('❌ 消息完成验证失败:', error)
              }
            }, 500) // 较短的延迟用于验证
          } catch (error) {
            console.error('❌ 消息完成处理失败:', error)
          }
        }
      }
    })
  } catch (error) {
    console.error('发送消息失败:', error)
  }
}

// 处理反馈
const handleFeedback = (messageId: string, feedback: any) => {
  console.log('处理反馈:', messageId, feedback)
  // 这里可以添加反馈处理逻辑
  updateFeedback(messageId, feedback)
}

// 处理停止生成
const handleStop = () => {
  console.log('停止生成消息')
  abortStreaming()
}

// 处理重新生成
const handleRegenerate = async (messageId: string) => {
  try {
    console.log('开始重新生成消息:', messageId)

    // 使用流式聊天组合式函数的重新生成功能
    await regenerateLastResponse()
  } catch (error) {
    console.error('重新生成失败:', error)
  }
}

// 组件挂载时初始化
onMounted(() => {
  initApp()
  // 添加窗口大小变化监听
  window.addEventListener('resize', handleResize)

  // 移动端特殊处理
  handleMobileOptimization()
})

// 组件卸载时清理事件监听
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})

// 移动端优化处理
const handleMobileOptimization = () => {
  // 检测是否为移动设备
  const isMobileDevice = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
    navigator.userAgent
  )

  if (isMobileDevice) {
    // 防止双击缩放
    let lastTouchEnd = 0
    document.addEventListener(
      'touchend',
      (e) => {
        const now = new Date().getTime()
        if (now - lastTouchEnd <= 300) {
          e.preventDefault()
        }
        lastTouchEnd = now
      },
      false
    )
  }
}
</script>

<style scoped>
.chat-app {
  display: flex;
  flex-direction: column;
  background: linear-gradient(to bottom, #f8fafc 0%, #f1f5f9 100%);
  height: 100%;
  width: 100%;
  /* 移除固定定位，改为相对定位以适应布局 */
  position: relative;
  overflow: hidden;
}

.app-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  position: relative;
  background: inherit;
  overflow: hidden;
  height: 100%;
  /* 使用视口高度减去header和padding */
  min-height: calc(
    100vh - var(--top-tool-height, 50px) - var(--tags-view-height, 35px) -
      var(--app-content-padding, 20px) * 2
  );
}

.main-content {
  flex: 1;
  display: flex;
  flex-direction: row;
  position: relative;
  overflow: hidden;
  height: 100%;
}

.chat-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-width: 0;
  transition: margin-left 0.3s ease;
  margin-left: 300px;
  background: inherit;
  position: relative;
  height: 100%;
  overflow: hidden;
}

.chat-main.full-width {
  margin-left: 0;
  width: 100%;
}

.chat-header {
  background: white;
  border-bottom: 1px solid #e5e7eb;
  padding: 1rem;
  flex-shrink: 0;
  position: sticky;
  top: 0;
  z-index: 10;
}

.sidebar-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 40;
}

/* 响应式设计 */
@media (min-width: 768px) and (max-width: 1023px) {
  .chat-main {
    margin-left: 240px;
  }
}

@media (max-width: 767px) {
  .main-content {
    flex-direction: column;
  }

  .chat-main {
    width: 100%;
    margin-left: 0;
    height: 100%;
  }

  .chat-main.full-width {
    margin-left: 0;
  }

  .app-container {
    /* 移动端使用完整视口高度 */
    min-height: 100vh;
  }
}
</style>
